<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>即时通讯系统</title>
    <link rel="stylesheet" href="./css/style.css" media="screen" type="text/css" />
</head>
<body>
<div id="convo">

    <ul class="chat-thread">
    </ul>

    <div class="chat-window">

        <input class="chat-window-message" name="chat-window-message" autocomplete="on" placeholder="请输入内容按回车键发送"
               type="text"/>
    </div>
</div>
<script src='./jquery.js' type="text/javascript"></script>
<script type="text/javascript">

    var wsUri = "ws://swoole.kinggui.com:9500/";
    var name = prompt("请填写昵称");
    //按下了回车键之后
    $(document).keypress(function (event) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            speak_to_all(); //插入发言
        }
    });

    testWebSocket();

    function testWebSocket() {
        //打开HTML5websocket
        websocket = new WebSocket(wsUri);

        //打开连接
        websocket.onopen = function (evt) {
            websocket.send('name:' + name);
        };
        //关闭连接
        websocket.onclose = function (evt) {
            append_speak("连接关闭");
        };
        //接收消息时触发
        websocket.onmessage = function (evt) {
            append_speak(evt.data);
        };
        //错误提示
        websocket.onerror = function (evt) {
            append_speak('连接失败');
        };

    }

    //消息内容发送到
    function speak_to_all() {
        var speak = $(".chat-window-message").val(); //获得文本框内容
        doSend(name + ':' + speak);
        //清除消息内容
        $(".chat-window-message").val('');
    }


    //往内容框中输入
    function append_speak(new_msg) {
        $(".chat-thread").append("<li>" + new_msg + "</li>");
        //滚动条下移到最后
        $(".chat-thread").scrollTop($('.chat-thread')[0].scrollHeight);
    }

    //向服务器发送消息
    function doSend(message) {
        websocket.send(message);
    }
</script>
</body>

</html>